#!/bin/bash
#
# fxplatform      This shell script takes care of starting and stopping
#               fxplatform (on 8003)
#
#
# chkconfig: 2345 99 20

# Source function library.
. /etc/init.d/functions

HOSTNAME=`hostname -f`

getpid() {
  echo `ps -ef|grep -w $PORT|grep -v grep|awk '{printf $2}'`
}

FXPLATFORM_DIR=/opt/pcs-server/pcs-server/WEB-INF
PIDFILE=/var/run/fxplatform.pid
prog=fxplatform
PORT=8003
PID=`getpid`

# "Spring Profile Options", invoking the process with correct parameter, "dev" under Vagrant
SPRING_PROFILE_OPTS=--spring.profiles.active=prod,platform,api
LOG_PATH=/mnt/pcslog

 if [ ! -e /mnt/pcslog ]; then
mkdir -p /mnt/pcslog
 fi

MY_CLASSPATH=$FXPLATFORM_DIR/classes:$JAVA_HOME/lib/rt.jar:$JAVA_HOME/lib/dt.jar

if [ -z $PID ] && [ -e ${PIDFILE} ]; then
  rm ${PIDFILE}
fi

if [ -z $PID ] && [ -e /var/lock/subsys/$prog ]; then
  rm -f /var/lock/subsys/$prog
fi

start() {
#	if  lsmod | grep -q vboxsf ; then
	PC_ENV=`echo ${HOSTNAME}|awk -F '.' '{print $3}'`
	if [[ ${PC_ENV} = 'foxitcloud' ]] ; then
		echo "Staring service under Vagrant..."
		SPRING_PROFILE_OPTS=--spring.profiles.active=dev,platform,api
		LOG_PATH=/var/log
	else
		echo "Starting service under non-Vagrant env..."
	fi

	PID=`getpid`

	if [ $PID ]; then
                echo Foxit Platform Server already running.
        else
		echo "begin to load jar"
		for jar in `ls ${FXPLATFORM_DIR}/lib/*.jar`
		do
       		 MY_CLASSPATH="$MY_CLASSPATH":"$jar"
		done
		export CLASSPATH=${MY_CLASSPATH}

                cd $FXPLATFORM_DIR
               java -Xmx2560M -Xms512M -XX:PermSize=64M -XX:MaxPermSize=512M -XX:+HeapDumpOnOutOfMemoryError com.foxitcloud.Application --server.port=$PORT ${SPRING_PROFILE_OPTS} --logging.file=${LOG_PATH}/fxplatform.log > ${LOG_PATH}/fxplatform-console.log  2>&1 &
               # java -Xms200M -Xmx1024M -Xss2M -XX:PermSize=64M -XX:MaxPermSize=128M com.foxitcloud.Application --server.port=$PORT ${SPRING_PROFILE_OPTS} --logging.file=/mnt/pcslog/fxplatform.log >/dev/null 2>&1 &
		echo $! > ${PIDFILE}
                RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
	    	  action $"Starting $prog: " /bin/true
	    	  touch /var/lock/subsys/$prog
		else
	    	  action $"Starting $prog: " /bin/false
		fi
                return $RETVAL
        fi

}

stop() {
	PID=`getpid`
	if [ -z $PID ]; then
	  echo "Foxit Platform Server already stopped"
	else
          kill -9 $PID
          action $"Stopping $prog: " /bin/true
	fi
        rm -f /var/lock/subsys/$prog ${PIDFILE}
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status -p ${PIDFILE} $prog
        ;;
    restart)
        stop
	sleep 5
        start
        ;;
    *)
        echo "Usage:  {start|stop|status|restart}"
        exit 1
        ;;
esac
exit $?
